using Dapper;
using HDLogCenter.Infrastructure.Config;
using Microsoft.Extensions.Options;
using MySqlConnector;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;

namespace HDLogCenter.Infrastructure.Mysql
{
    public class DbService : IDbService
    {
        private readonly string _connectionString;

        public DbService(IOptionsMonitor<ConnectionStrings> connectionString)
        {
            _connectionString = connectionString.CurrentValue.Mysql;
        }

        public IDbConnection GetConnection()
        {
            return new MySqlConnection(_connectionString);
        }

        public async Task<T> QuerySingleOrDefaultAsync<T>(string sql, object param = null)
        {
            using (var connection = GetConnection())
            {
                return await connection.QuerySingleOrDefaultAsync<T>(sql, param);
            }
        }

        public async Task<IEnumerable<T>> QueryAsync<T>(string sql, object param = null)
        {
            using (var connection = GetConnection())
            {
                return await connection.QueryAsync<T>(sql, param);
            }               
        }

        public async Task<int> ExecuteAsync(string sql, object param = null)
        {
            using (var connection = GetConnection())
            {
                return await connection.ExecuteAsync(sql, param);
            }
        }

        public async Task<long> ExecuteScalarAsync(string sql, object param = null)
        {
            using (var connection = GetConnection())
            {
                return await connection.ExecuteScalarAsync<long>(sql, param);
            }
        }
    }
}
